import axios from 'axios';

export default {
    data() {
        return {
            isDialogVisible: false,
            formData: {
                taskName: '',
                taskType: 'cantonese',
            },
            taskSections: [],
            selectedRecordings: [],
            globalCurrentPage: 1,
            globalPageSize: 10,
            selectedFiles: [], // 存储多个文件
            loading: false,
            activeMenu: 'task',
            menus: [
                {id: 'task', name: '任务管理', icon: 'fa-tasks'},
                {id: 'analysis', name: '数据分析', icon: 'fa-chart-bar'},
                {id: 'settings', name: '系统设置', icon: 'fa-cog'}
            ],
            isDownloading: false, // 下载状态
            downloadProgress: 0, // 下载进度
            isSidebarCollapsed: false, // 侧边栏收放状态
        };
    },
    created() {
        this.fetchTasks();
    },
    computed: {
        paginatedTasks() {
            const start = (this.globalCurrentPage - 1) * this.globalPageSize;
            const end = start + this.globalPageSize;
            return this.taskSections.slice(start, end).map((section) => {
                // 检查该任务下所有音频是否都被选中
                section.isAllSelected = section.audios.every((audio) =>
                    this.selectedRecordings.includes(audio.id)
                );
                return section;
            });
        },
    },
    methods: {
        async fetchTasks() {
            this.loading = true;
            try {
                const response = await axios.get('http://10.10.20.54:8000/audios/status/');
                const tasks = response.data;
                this.taskSections = tasks.map((task) => ({
                    title: task.audio_name,
                    isAllSelected: false,
                    isExpanded: false,
                    audios: task.file_list.map((audio, index) => ({
                        id: `${task.audio_name}-${index}`,  // 生成唯一ID
                        name: typeof audio === 'string'? audio : audio.filename,
                        progress: typeof audio === 'string'? 0 : audio.progress,
                        file_path: typeof audio === 'string'? null : audio.download_path
                    }))
                }));
            } catch (error) {
                console.error('获取任务列表失败:', error);
                this.$message.error('获取任务列表失败');
            } finally {
                this.loading = false;
            }
        },

        handleFileChange(event) {
            const files = event.target.files;
            const allowedTypes = ['.wav', '.mp3', '.ogg', '.flac', '.aac', '.m4a'];
            const validFiles = this.selectedFiles;
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                const fileExtension = '.' + file.name.split('.').pop().toLowerCase();
                if (allowedTypes.includes(fileExtension)) {
                    validFiles.push(file);
                } else {
                    this.$message.error(`文件 ${file.name} 格式不支持，仅支持 .wav、.mp3、.ogg、.flac、.aac、.m4a 格式的文件`);
                }
            }
            this.selectedFiles = validFiles;
            console.log(this.selectedFiles);
        },

        async handleSubmit() {
            if (!this.formData.taskName.trim()) {
                this.$message.error('请输入任务名称');
                return;
            }
            if (this.selectedFiles.length === 0) {
                this.$message.error('请选择文件');
                return;
            }

            const formData = new FormData();
            formData.append('audio_name', this.formData.taskName);
            for (let i = 0; i < this.selectedFiles.length; i++) {
                formData.append('files', this.selectedFiles[i]);
            }

            try {
                const response = await axios.post('http://10.10.20.54:8000/audios/', formData);
                const { audio_name, file_list } = response.data;
                console.log(response.data);
                const newSection = {
                    title: audio_name,
                    isAllSelected: false,
                    isExpanded: true,
                    audios: file_list.map((filename, index) => ({
                        id: `${audio_name}-${index}`,
                        name: filename,
                        progress: 0
                    }))
                };
                this.taskSections.push(newSection);
                this.isDialogVisible = false;
                this.formData.taskName = '';
                this.selectedFiles = [];

                // 直接重新获取完整任务列表（确保数据最新）
                await this.fetchTasks();
                this.$message.success('任务创建成功');
            } catch (error) {
                console.error('文件上传失败:', error);
                this.$message.error('文件上传失败');
            }
        },
        handleGlobalSizeChange(pageSize) {
            this.globalPageSize = pageSize;
            console.log(`全局每页显示 ${pageSize} 个任务`);
        },
        handleGlobalCurrentChange(currentPage) {
            this.globalCurrentPage = currentPage;
            console.log(`全局当前页: ${currentPage}`);
        },
        async refreshTask(section) {
            // 使用ref或直接传递事件对象更可靠
            const refreshIcon = event.currentTarget.querySelector('i');
            if (!refreshIcon) return;

            refreshIcon.classList.add('fa-spin');

            try {
                const response = await axios.get(
                    `http://10.10.20.54:8000/audios/status/?audio_name=${section.title}`
                );
                console.log(response.data);
                const fileList = response.data.file_list;
                // 更新所有音频进度
                section.audios.forEach(audio => {
                    // 生成与 fetchTasks 中相同规则的唯一 id
                    const uniqueId = `${section.title}-${section.audios.indexOf(audio)}`;
                    const file = fileList.find(f => {
                        // 生成服务器端音频对应的唯一 id
                        const serverId = `${section.title}-${fileList.indexOf(f)}`;
                        return serverId === uniqueId;
                    });
                    if (file) {
                        audio.progress = file.progress;
                        audio.file_path = file.download_path;
                    }
                });
            } catch (error) {
                console.error('刷新任务失败', error);
                this.$message.error('刷新任务失败');
            } finally {
                // 添加延迟确保动画可见
                setTimeout(() => {
                    refreshIcon.classList.remove('fa-spin');
                }, 500);
            }
        },
        toggleSelectAll(section) {
            if (section.isAllSelected) {
                // 选中该任务下所有音频
                section.audios.forEach((audio) => {
                    if (!this.selectedRecordings.includes(audio.id)) {
                        this.selectedRecordings.push(audio.id);
                    }
                });
            } else {
                // 取消选中该任务下所有音频
                section.audios.forEach((audio) => {
                    const index = this.selectedRecordings.indexOf(audio.id);
                    if (index > -1) {
                        this.selectedRecordings.splice(index, 1);
                    }
                });
            }
        },

        // 切换菜单
        switchMenu(menuId) {
            this.activeMenu = menuId;
            // 如果是收起状态，点击后自动展开
            if (!this.isSidebarVisible) {
                this.isSidebarVisible = true;
            }
        },

        async downloadAudio(audio) {
            try {
                this.isDownloading = true;
                this.downloadProgress = 0;
                const formData = new FormData();
                formData.append('file_path', audio.file_path);
                console.log(audio.file_path);

                const response = await axios.post('http://10.10.20.54:8000/audios/download/', formData, {
                    responseType: 'blob',
                    onDownloadProgress: (progressEvent) => {
                        const totalLength = progressEvent.lengthComputable? progressEvent.total : null;
                        if (totalLength) {
                            this.downloadProgress = Math.round((progressEvent.loaded / totalLength) * 100);
                        }
                    }
                });

                const url = window.URL.createObjectURL(new Blob([response.data]));
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', audio.name);
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                this.$message.success(`${audio.name} 下载成功`);
            } catch (error) {
                console.error('下载音频失败:', error);
                this.$message.error('下载音频失败');
            } finally {
                this.isDownloading = false;
                this.downloadProgress = 0;
            }
        },
        async startAudioProcessing() {
            if (this.selectedRecordings.length === 0) {
                console.log(this.selectedRecordings);
                this.$message.error('请至少选择一个音频进行转换');
                return;
            }

            const audioDict = {};
            this.taskSections.forEach(section => {
                const selectedAudios = section.audios.filter(audio => this.selectedRecordings.includes(audio.id));
                if (selectedAudios.length > 0) {
                    audioDict[section.title] = selectedAudios.map(audio => audio.name);
                }
            });

            try {
                const response = await axios.post('http://10.10.20.54:8000/audios/process/', {
                    audio_dict: audioDict
                });
                this.$message.success(response.data.message);
            } catch (error) {
                console.error('开始音频转换失败:', error);
                this.$message.error('开始音频转换失败');
            }
        },
        async batchDownload() {
            if (this.selectedRecordings.length === 0) {
                this.$message.error('请至少选择一个音频进行下载');
                return;
            }
            const selectedAudios = [];
            this.taskSections.forEach(section => {
                section.audios.forEach(audio => {
                    if (this.selectedRecordings.includes(audio.id)) {
                        selectedAudios.push(audio);
                    }
                });
            });
            for (let i = 0; i < selectedAudios.length; i++) {
                await this.downloadAudio(selectedAudios[i]);
            }
        },
        toggleSidebar() {
            this.isSidebarCollapsed = !this.isSidebarCollapsed; // 切换侧边栏收放状态
        },
    },
};
